<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Dathang extends MY_Controller { 
	 
	public function __construct()
    {
        parent::__construct();	
		$this->load->model('Dathang_model');
		$this->loadtrangchu("");  
		$this->load->library('session'); 
		
	}
	
	public function DatHang_K()
	{  
		$this->load->library('form_validation');
		$this->data['title']=$this->lang->line('TD_DatHang');//"Đặt hàng";
		$this->data['DH_ThongBao']="";
		$this->getURL();
		$this->LoadPage('trangchu/DatHang_K', $this->data); 
	}
	public function DatHang()
	{   
		$this->load->library('form_validation');
		$this->data['title']=$this->lang->line('TD_DatHang');//"Đặt hàng";
		$this->data['DH_ThongBao']="";
		$this->getURL();			
		$this->LoadPage('trangchu/DatHang', $this->data);	 
	} 
	public function XacNhan($Loai)
	{   
		$this->load->library('form_validation'); 
		$this->data['title']=$this->lang->line('TD_ThongTinXN');//"Xác nhận thông tin";
		$this->data['DatHang']=	$this->input->post();
		$this->data['url']=$this->session->userdata('S_URL');  
		$this->session->unset_userdata("S_DatHang");// xóa thông tin trước trong session
		$this->session->set_userdata("S_DatHang",$this->data['DatHang']); // gán vào sesion  
		//không đăng nhập
		if($Loai==2){  
			if($this->form_validation->run('frmDatHangK')==false ){
				redirect($this->data['language']."/trangchu/DatHang_K");	
			}
			$DatHang=$this->session->userdata('S_DatHang'); 
			$Str   =	     " <div class='ThongTin'> <a >".$this->lang->line('DH_TenNguoiGui')."  : </a> <a > ".$DatHang['HoTenNG']."</a> </div> " ;
			$Str   =    $Str." <div class='ThongTin'> <a >".$this->lang->line('DH_SDTGui')."       : </a> <a > ".$DatHang['SDTG']."</a> </div> " ;
			$Str   =	$Str." <div class='ThongTin'> <a >".$this->lang->line('DH_MailGui')."      : </a> <a > ".$DatHang['MailG']."</a> </div> " ;
			$Str   =	$Str." <div class='ThongTin'> <a >".$this->lang->line('DH_TenNguoiNhan')." : </a> <a > ".$DatHang['HoTenNN']."</a> </div> " ;
			$Str   =	$Str." <div class='ThongTin'> <a >".$this->lang->line('DH_DiaChiNhan')."   : </a> <a > ".$DatHang['DiaChiNhan']."</a> </div> "; 
			$Str   =	$Str." <div class='ThongTin'> <a >".$this->lang->line('DH_SDTNhan')."      : </a> <a > ".$DatHang['SDTN']."</a> </div> "; 
			$Str   =	$Str." <div class='ThongTin'> <a >".$this->lang->line('DH_MailNhan')."     : </a> <a > ".$DatHang['MailN']."</a> </div> "; 
			$Str   =	$Str." <div class='ThongTin'> <a >".$this->lang->line('DH_GhiChu')."       : </a> <a > ".$DatHang['GhiChu']."</a> </div> "; 
			$Str   =	$Str." <br /> ";
			$Str   =	$Str." <div class='ThongTin'> ".$this->lang->line('chu_y')."</div> "; 
			$this->data['Str']=	$Str; 
			$this->data['DH_Url']=base_url()."index.php/".$this->uri->segment(1)."/Dathang/ThanhToan/2";
		}
		//dã đăng nhập
		if($Loai==1){  
		if($this->form_validation->run('frmDatHang')==false ){
				redirect($this->data['language']."/trangchu/DatHang");	
			}
			$DatHang=$this->session->userdata('S_DatHang'); 
			$Str   =	     " <div class='ThongTin'> <a >".$this->lang->line('tennhan')."     : </a> <a > ".$DatHang['HoTenNN']."</a> </div> " ;
			$Str   =    $Str." <div class='ThongTin'> <a >".$this->lang->line('diachinhan')."  : </a> <a > ".$DatHang['DiaChiNhan']."</a> </div> " ;
			$Str   =	$Str." <div class='ThongTin'> <a >".$this->lang->line('sdtnhan')."     : </a> <a > ".$DatHang['SDT']."</a> </div> " ;
			$Str   =	$Str." <div class='ThongTin'> <a >".$this->lang->line('mailnhan')."    : </a> <a > ".$DatHang['Mail']."</a> </div> " ;
			$Str   =	$Str." <div class='ThongTin'> <a >".$this->lang->line('ghichu')."      : </a> <a > ".$DatHang['GhiChu']."</a> </div> "; 
			$Str   =	$Str." <br /> ";
			$Str   =	$Str." <div class='ThongTin'> ".$this->lang->line('chu_y')."</div> "; 
			$this->data['Str']=	$Str; 
			$this->data['DH_Url']=base_url()."index.php/".$this->uri->segment(1)."/Dathang/ThanhToan/1";
		}
		$this->LoadPage('trangchu/XacNhanDatHang', $this->data);
	}
	//==================================
	//Than Toán
	public function ThanhToan($Loai) {
		$Dathang=$this->session->userdata('S_DatHang');
		if(empty($Dathang)){
			redirect($url); 
			return;
		}
		if($Loai==1){
		  $this->ThanhToan_Da();
		  return;
		}
		if($Loai==2){
		   $this->ThanhToan_Khong();
		   return;
		}
	}
	//==================================
	//thah toán khi không đăng nhập
	public function ThanhToan_Khong(){//không đăng nhập 
		 //thêm vào bảng dondathang
		 $dt_DatHang=$this->session->userdata('S_DatHang'); 
		 $MaTK = $this->Them_TạiKhoan($dt_DatHang); 
		 print_r($dt_DatHang);
		 if(empty($MaTK)) { 
		 	$this->data['title']="Đặt hàng";
			$this->data['DH_ThongBao']=$this->lang->line('DH_ThongBao');//"Bạn chưa đăng nhập mới thanh toán được.";
			$this->getURL();			
			$this->LoadPage('trangchu/DatHang', $this->data);	
			return; 
		 } 
		 $Dathang=array( 
					'NguoiNhan'   =>$dt_DatHang['HoTenNN'],
					'DiaChi'      =>$dt_DatHang['DiaChiNhan'],
					'NgayDatHang' =>$this->LayNgay(),
					'SoDienThoai' =>$dt_DatHang['SDTN'],
					'Email'       =>$dt_DatHang['MailN'],
					'GhiChu'      =>$dt_DatHang['GhiChu'],
					'TriGia'      =>$this->cart->total(),
					'Ma_TK'       =>$MaTK,
					'thanhtoan'     =>0,
					'TinhTrang'  =>'1'
					);  
		 $id=$this->Dathang_model->Them($Dathang);
		 $this->session->set_userdata("S_id_DH",$id);
		 //Thêm vào bảng ddh_sp 
		 if($this->Them_ChiTiet($id)==false){// không thanh công thì xóa hết
			 $this->Dathang_model->Xoa_CT($id);
			 $this->Dathang_model->Xoa ($id);  
			 $this->Dathang_model->MaTK($id);
		 }else{  
			 $this->MuaHang();// gọi hàm thanh toán 
		 }
	}
	
	//==================================
	//Them chi tiết đơn dăt hàng
	public function Them_TạiKhoan($TaiKhoan){ 
		$TK=array(  
				'TenTaiKhoan' =>random_string('numeric', 8),
				'MatKhau'     =>random_string('numeric', 8),
				'HoTen'       =>$TaiKhoan['HoTenNG'],
				'DiaChi'      =>"rổng",
				'SoDienThoai' =>$TaiKhoan['SDTG'],
				'Email'       =>$TaiKhoan['MailG'], 
				'TrangThai'   =>1,
				'Quyen'       =>2
				);  
		$id=$this->Dathang_model->ThemTaiKhoan($TK);  
		return $id;
	}
	
	//==================================
	//thah toán khi đã đăng nhập
	public function ThanhToan_Da(){//dã đăng nhập  
		 $dt_DatHang=$this->session->userdata('S_DatHang');  
		 $TaiKhoan = $this->session->userdata('TaiKhoan'); 
		 if(empty($TaiKhoan)) { 
		 	$this->data['title']="Đặt hàng";
			$this->data['DH_ThongBao']=$this->lang->line('DH_ThongBao');//"Mục này đăng nhập mới thanh toán được.";
			$this->getURL();			
			$this->LoadPage('trangchu/DatHang', $this->data);	
			return; 
		 } 
		 $Dathang=array( 
					'NguoiNhan'   =>$dt_DatHang['HoTenNN'],
					'DiaChi'      =>$dt_DatHang['DiaChiNhan'],
					'NgayDatHang' =>$this->LayNgay(),
					'SoDienThoai' =>$dt_DatHang['SDT'],
					'Email'       =>$dt_DatHang['Mail'],
					'GhiChu'      =>$dt_DatHang['GhiChu'],
					'TriGia'      =>$this->cart->total(),
					'Ma_TK'       =>$TaiKhoan['MaTK'],
					'thanhtoan'     =>0,
					'TinhTrang'  =>'1'
					);  
		 $id=$this->Dathang_model->Them($Dathang);
		 $this->session->set_userdata("S_id_DH",$id);
		 //Thêm vào bảng ddh_sp 
		 if($this->Them_ChiTiet($id)==false){// không thanh công thì xóa hết
			 $this->Dathang_model->Xoa_CT($id);
			 $this->Dathang_model->Xoa ($id);  
		 }else{  
			 $this->MuaHang();// gọi hàm thanh toán 
		 }
	}
	
	//==================================
	//Them chi tiết đơn dăt hàng
	public function Them_ChiTiet($id){
		if($id>0){
			foreach ($this->cart->contents() as $items): 
				 $Dathang_CT=array( 
						'Ma_DDH'  =>$id,
						'Ma_SP'   =>$items['id'],
						'SoLuong' =>$items['qty'] 
						);  
						
			 	$id_CT=$this->Dathang_model->Them_CT($Dathang_CT); 
				$Dathang_CT=""; 
				if($id_CT<=0){ 
					return false;
				}
			endforeach;
		}
		return true;
	}
	//==================================
	//mua hàng
	public function MuaHang(){ 
		$this->load->helper('string');
		$config['business']          = 'dhdongthap@gmail.com';
		$config['cpp_header_image']  = ''; 
		$config['return']            = base_url().'/index.php/vi/Dathang/HoanThanh';
		$config['cancel_return']     = base_url().'/index.php/vi/Dathang/ThatBai';
		$config['notify_url']        = 'process_payment.php'; 
		$config['production']        = false; 
		$config["invoice" ]          = random_string('numeric', 8);  
		$this->load->library('paypal',$config);  
		foreach ($this->cart->contents() as $items):
			$Gia1 = round($items['price']/20000,2);// chuyen sang USDs
			$this->paypal->add( $items['name'],  $Gia1,  $items['qty']);  
		endforeach;  
		$this->paypal->pay(); //Proccessthe payment
	}
	//==================================
	//hoàn thành, khi mua hàng thành công
	public function HoanThanh() {
		$this->data["ThongTinThanToan"]=$_POST;
		$ThongTinThanToan=array( 
						'NgayThanhToan'   =>$this->data["ThongTinThanToan"]['payment_date'],
						'Email'   =>$this->data["ThongTinThanToan"]['payer_email'],
						'MaGiaoDich'   =>$this->data["ThongTinThanToan"]['invoice'],
						'TriGia'   =>$this->data["ThongTinThanToan"]['payment_gross'], 
						'Ma_DDH'   =>$this->session->userdata('S_id_DH'),						
						'Ma_PT'   =>1,
						'TiGia' =>20000
						);  
		$id_TTTT=$this->Dathang_model->Them_ThongTinThanhToan($ThongTinThanToan);  
		$this->UpTT_ThanhToan($this->session->userdata('S_id_DH'),1);
		 
		// up lượt đăt hàng
		foreach ($this->cart->contents() as $items): 
			 $this->ThemLuotDatHang($items['id'],$items['qty']);
		endforeach;   
		
		$this->cart->destroy();// thành công thì xóa rổng giỏ hàng 
		$this->session->unset_userdata("S_id_DH"); 
		
		$this->data['title']="Giỏ hàng";
		$this->data['GH_ThongBao']= $this->lang->line('GH_ThongBao');//"Bạn đã mua thành công!"
		$this->LoadPage('trangchu/GioHang', $this->data);  
	}
	//==================================
	//thất bại, khi mua hàng không thành công
	public function ThatBai() {
		$this->UpTT_ThanhToan($this->session->userdata('S_id_DH'),2);
		$this->Dathang_model->Xoa_CT($this->session->userdata('S_id_DH'));
		$this->Dathang_model->Xoa ($this->session->userdata('S_id_DH')); 
		$this->LoadPage('trangchu/XacNhanDatHang', $this->data);
	}
	//==================================
	//úp số sản phẩm đac được mua
	public function ThemLuotDatHang($MaSP, $SoLuong) {  
		    $SanPham=$this->Dathang_model->LuotDatHang($MaSP);  
			$SoLuong1 = $SoLuong +$SanPham['soluotdathang']; 
			$SoLuong2 = $SanPham['SoLuong'] - $SoLuong;
			$LuotDatHang=array( 
						'MaSP'   		=> $MaSP,
						'SoLuotDatHang' => $SoLuong1,
						'SoLuong'       => $SoLuong2
						);	
			 $id_TTTT=$this->Dathang_model->UpLuotDatHang($LuotDatHang); 
	}
	//==================================
	//úp trạng thái thanh toán
	public function UpTT_ThanhToan($MaDDH, $TrangThai){  //1 là đã thanh toán, 2 là chưa thanh toán
		 
		$TT_ThanhToan=array( 
						'MaDDH'   		=>$MaDDH,
						'thanhtoan' =>$TrangThai 
						);
		$id_TTTT=$this->Dathang_model->UpThanhToan($TT_ThanhToan); 
	}
	
}